import { fabric } from 'fabric';

import ObjectPool from './ObjectPool';

class Rect extends fabric.Rect {
  constructor(options = {}) {
    super({
      left: 100,
      top: 100,
      width: 100,
      height: 100,
      fill: '#ffffff',
      strokeWidth: 1,
      stroke: '#000000',
      selectable: true,
      cornerSize: 10,
      transparentCorners: false,
      hasRotatingPoint: true,
      padding: 5,
      id: '',  // 添加id属性
      ...options,
    });

    // 确保控制点颜色与边框颜色一致
    this.set({
      cornerColor: this.stroke,
      borderColor: this.stroke,
    });
  }

  // 更新属性
  updateProps(props) {
    this.set(props);
    if (props.stroke) {
      this.set({
        cornerColor: props.stroke,
        borderColor: props.stroke,
      });
    }
    this.canvas?.requestRenderAll();
    return this;
  }

  // 移到顶层
  bringToFront() {
    if (this.canvas) {
      this.canvas.bringToFront(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 移到底层
  sendToBack() {
    if (this.canvas) {
      this.canvas.sendToBack(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 删除自身
  remove() {
    if (this.canvas) {
      this.canvas.remove(this);
      this.canvas.requestRenderAll();
    }
  }

  // 设置大小
  setSize(size) {
    const scale = size / 100;
    this.scale(scale);
    this.canvas?.requestRenderAll();
    return this;
  }
}

// 创建一个全局的矩形对象池
const rectPool = new ObjectPool(() => new Rect());

// 导出Rect类和rectPool
export { Rect, rectPool };
export default Rect;
